package vn.com.bookstore.fragment;

import vn.com.bookstore.BookStoreApplication;
import vn.com.bookstore.Config;
import vn.com.bookstore.ConnectActivity;
import vn.com.bookstore.ObjectFragment;
import vn.com.bookstore.R;
import vn.com.bookstore.model.Book;
import vn.com.bookstore.model.Page;
import vn.com.bookstore.network.NetworkAdapter;
import vn.com.bookstore.network.NetworkAdapter.OnNetworkListener;
import vn.com.bookstore.util.imageview.ZoomableImageView;
import vn.com.bookstore.util.lazzyloading.ImageLoaderView;
import vn.com.bookstore.util.scrollview.ObservableScrollView;
import vn.com.bookstore.util.scrollview.ScrollViewListener;
import vn.com.bookstore.util.textview.JustifiedTextView;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

@SuppressLint("ValidFragment")
public class PageBookFragment extends ObjectFragment implements ScrollViewListener, OnNetworkListener {
	public static final String TAG = "PageBookFragment";

	public static final int FLAG_ZOOM_IN = 0;
	public static final int FLAG_ZOOM_OUT = 1;

	public static final int TEXT_SIZE_MIN = 13;
	public static final int TEXT_SIZE_MAX = 20;
	public static float currentSize = TEXT_SIZE_MIN;

	public int lastScrollY = 0;

	View parent;
	LinearLayout layoutReadView;
	JustifiedTextView content;
	ZoomableImageView image;
	ZoomLayout zoomLayout;
	ObservableScrollView scrollView;
	RelativeLayout layoutControl;

	ControlThread mControlThread;

	Bundle bundle;
	Page page;
	boolean isComics=false;;

	public PageBookFragment() {
		mControlThread = new ControlThread();
	}

	public PageBookFragment(Page page,Book book) {
		setData(page,book.isComics());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//		Log.e("PageBookFragment", "oncreateView");

		parent = inflater.inflate(R.layout.fragment_book_view, container, false);
		layoutReadView = (LinearLayout) parent.findViewById(R.id.layout_read_view);
		if (parent != null) {
			content = (JustifiedTextView) parent.findViewById(R.id.content);
			image = (ZoomableImageView) parent.findViewById(R.id.image);
		}
		zoomLayout = new ZoomLayout(getActivity(), parent.findViewById(R.id.layout_zoom));
		scrollView = (ObservableScrollView) parent.findViewById(R.id.scrollview);
		layoutControl = (RelativeLayout) parent.findViewById(R.id.layout_bottom);

		scrollView.setScrollViewListener(this);

		bundle = getArguments();
		if (bundle != null) {
			page = (Page) bundle.getSerializable(Page.TAG);
			
		}

		// resume from Preference
		if (mApplication == null)
			mApplication = (BookStoreApplication) getActivity().getApplication();
		currentSize = mApplication.getValue(BookStoreApplication.KEY_TEXT_SIZE, Float.valueOf(TEXT_SIZE_MIN));
		if (page.id == mApplication.getValue(BookStoreApplication.KEY_PAGE_ID, 0)) {
			lastScrollY = mApplication.getValue(BookStoreApplication.KEY_LAST_Y, 0);
			((ImageView) parent.findViewById(R.id.bookmark)).setImageResource(R.drawable.icon_rating_big_on);
			scrollTo(lastScrollY);
		}
		startAnimControl(android.R.anim.fade_in, true);

		loadData(false);

		// setTextColor(mApplication.getValue(BookStoreApplication.KEY_COLOR_LAYOUT,
		// Color.BLACK),
		// mApplication.getValue(BookStoreApplication.KEY_COLOR_TEXT,
		// Color.WHITE));
		
		return parent;
	}

	public void setTextColor(int layoutColor, int textColor) {
		layoutReadView.setBackgroundColor(layoutColor);
		content.setTextColor(textColor);
		mApplication.setValue(BookStoreApplication.KEY_COLOR_LAYOUT, layoutColor);
		mApplication.setValue(BookStoreApplication.KEY_COLOR_TEXT, textColor);
	}

	@Override
	public void loadData(final boolean forceLoad) {
		getContent(page.id, forceLoad);
	}

	public void getContent(final int pageId, final boolean forceLoad) {
		// get content of page
		new Thread() {
			public void run() {
				NetworkAdapter net = new NetworkAdapter(mApplication, mHandler, PageBookFragment.this);
				Config.NetObject obj = Config.BookStore.getUrlContent(pageId, 0);
				net.sendHttpGet(ConnectActivity.METHOD_GET_CONTENT, obj.url, obj.param, forceLoad);
			};
		}.start();
		refreshUI();
	}

	@Override
	public int getCurrentPosition() {
		return lastScrollY;
	}

	// called before onCreateView
	public void setData(Page page,boolean isComics) {
//		Log.e("PageBookFragment", "setData");
		this.page = page;
		this.isComics = isComics;

		if (bundle == null)
			bundle = new Bundle();
		bundle.putSerializable(Page.TAG, page);
		setArguments(bundle);
		refreshUI();
	}

	public void refreshUI() {
		if (content != null) {
			if (isComics) {
				scrollView.setVisibility(View.GONE);
				image.setVisibility(View.VISIBLE);
				if(page.isImage()){
					ImageLoaderView loader = new ImageLoaderView(mApplication);
					Log.e("ImageLoaderView", "url="+Config.getUrlImage(page.getImageLink()));
					loader.DisplayImage(Config.getUrlImage(page.getImageLink()), image);
				}
			} else {
				scrollView.setVisibility(View.VISIBLE);
				image.setVisibility(View.GONE);
				// content.loadData(page.content, "", "");
				content.setText(page.content);
				content.setTextSize((int) currentSize);
				scrollTo(lastScrollY);
			}
		}
	}

	public void scrollTo(int y) {
		if (y == 0)
			return;
		lastScrollY = y;
		if (scrollView != null) {
//			Log.e("____khac.pvan", "last scroll y: " + lastScrollY);
			scrollView.scrollTo(0, lastScrollY);
		}
	}

	public void zoom(int flag) {
		String message = "";
		switch (flag) {
		case FLAG_ZOOM_IN:
			if (currentSize < TEXT_SIZE_MAX) {
				currentSize++;
				message = String.format(getResources().getString(R.string.zoom_current), currentSize);
			} else
				message = getResources().getString(R.string.zoom_in_max);
			break;
		case FLAG_ZOOM_OUT:
			if (currentSize > TEXT_SIZE_MIN) {
				currentSize--;
				message = String.format(getResources().getString(R.string.zoom_current), currentSize);
			} else {
				message = getResources().getString(R.string.zoom_in_min);
			}
			break;
		default:
			break;
		}
		content.setTextSize((int) currentSize);
		OnZoomListener listener = (OnZoomListener) this.getActivity();
		if (listener != null)
			listener.onZoomChange(currentSize);
		Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
	}

	public void setTextCurrentSize(float textSize) {
		currentSize = textSize;
		if (content == null)
			return;
		content.setTextSize((int) currentSize);
	}

	@Override
	public void btnClicked(View v) {
		switch (v.getId()) {
		case R.id.bookmark:
			((ImageView) v).setImageResource(R.drawable.icon_rating_big_on);
			mApplication.setValue(BookStoreApplication.KEY_PAGE_ID, page.id);
			mApplication.setValue(BookStoreApplication.KEY_LAST_Y, lastScrollY);
			Toast.makeText(this.getActivity(), getString(R.string.bookmark) + page.title, Toast.LENGTH_SHORT).show();
			break;
		case R.id.changeText:
			if (mApplication.getValue(BookStoreApplication.KEY_COLOR_TEXT, Color.WHITE) == Color.WHITE) {
				setTextColor(Color.WHITE, Color.BLACK);
			} else {
				setTextColor(Color.BLACK, Color.WHITE);
			}

			break;
		default:
			break;
		}

	}

	public class ZoomLayout implements OnClickListener {
		View layout;
		ImageButton btnPlus;
		ImageButton btnSub;

		public ZoomLayout(Context context, View layoutParent) {
			layout = layoutParent;
			btnPlus = (ImageButton) layout.findViewById(R.id.btn_zoom_in);
			btnSub = (ImageButton) layout.findViewById(R.id.btn_zoom_out);

			btnPlus.setOnClickListener(this);
			btnSub.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_zoom_in:
				PageBookFragment.this.zoom(FLAG_ZOOM_IN);
				break;
			case R.id.btn_zoom_out:
				PageBookFragment.this.zoom(FLAG_ZOOM_OUT);
				break;
			default:
				break;
			}
		}
	}

	@Override
	public boolean onKeyDown(int keycode, KeyEvent e) {
		switch (keycode) {
		case KeyEvent.KEYCODE_MENU:
			startAnimControl(android.R.anim.fade_in, true);
			return true;
		}

		return super.onKeyDown(keycode, e);
	}

	@Override
	public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
		lastScrollY = y;
		// startAnimControl(android.R.anim.fade_in, true);
	}

	public interface OnZoomListener {
		public void onZoomChange(float currentTextSize);
	}

	@Override
	public void onSizeChanged(ObservableScrollView scrollView, int w, int h, int oldw, int oldh) {
		if (lastScrollY == 0) {
			lastScrollY = mApplication.getValue(BookStoreApplication.KEY_LAST_Y, 0);
			scrollTo(lastScrollY);
		}

	}

	public void startAnimControl(final int animId, final boolean show) {
		layoutControl.post(new Runnable() {

			@Override
			public void run() {
				try {
					Animation anim = AnimationUtils.loadAnimation(PageBookFragment.this.getActivity(), animId);
					anim.setAnimationListener(new AnimationListener() {

						@Override
						public void onAnimationStart(Animation animation) {

						}

						@Override
						public void onAnimationRepeat(Animation animation) {

						}

						@Override
						public void onAnimationEnd(Animation animation) {
							if (show) {
								layoutControl.setVisibility(View.VISIBLE);

								if (mControlThread == null) {
									mControlThread = new ControlThread();
									mControlThread.start();
								} else if (!mControlThread.isAlive) {
									try {
										mControlThread.start();
									} catch (IllegalThreadStateException e) {
										mControlThread = new ControlThread();
										mControlThread.start();
									}
								}
							} else {
								layoutControl.setVisibility(View.INVISIBLE);
							}

						}
					});
					layoutControl.startAnimation(anim);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	class ControlThread extends Thread {
		public long startTime = 0;
		public boolean isAlive = false;

		public ControlThread() {
			isAlive = false;
		}

		@Override
		public void run() {
			super.run();
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (isAlive) {
				startAnimControl(android.R.anim.fade_out, false);
				isAlive = false;
			}
		}

		@Override
		public synchronized void start() {
			isAlive = true;
			super.start();

		}

		public void kill() {
			isAlive = false;
		}
	}

	@Override
	public void onResponse(int idMethod, boolean isSuccess, String json) {
		if (isSuccess) {
			switch (idMethod) {
			case ConnectActivity.METHOD_GET_CONTENT:
				page.content = json+"";
				if (content != null) {
					if (isComics) {
						scrollView.setVisibility(View.GONE);
						image.setVisibility(View.VISIBLE);
					} else {
						scrollView.setVisibility(View.VISIBLE);
						image.setVisibility(View.GONE);
						// content.loadData(page.content, "", "");
						content.setText(page.content);
						content.setTextSize((int) currentSize);
						scrollTo(lastScrollY);
					}
				}
				break;
			default:
				break;
			}

		}
		refreshUI();
	}
}
